//
//  TTCouponViewController.m
//  TaoTuo
//
//  Created by admin on 2019/9/29.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTCouponViewController.h"
#import "TTCouponViewCell.h"
#import "TTCouponModel.h"

#import "TTInvalidCouponViewController.h"

#define bottomViewH 50

static NSString *cellID = @"coupon_cell_id";

@interface TTCouponViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITextField *tf;
@property (nonatomic, assign) NSInteger couponState;
@property (nonatomic, assign) BOOL needLoadData;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL showNotUseCoupon;    // 是否显示不使用优惠券，默认不显示

@end

@implementation TTCouponViewController

- (instancetype)initWithDataArray:(NSArray *)dataArray showNotUseCoupon:(BOOL)showNotUseCoupon
{
    self = [super init];
    if (self) {
        [self.dataArray removeAllObjects];
        if (dataArray.count > 0) {
            [self.dataArray addObjectsFromArray:dataArray];
        }
        self.showNotUseCoupon = showNotUseCoupon;
        [self setupFooterView];
        self.needLoadData = NO;
        [self.tableView reloadData];
        
    }
    return self;
}

- (instancetype)initWithCouponState:(NSInteger)couponState
{
    self = [super init];
    if (self) {
        
        self.couponState = couponState;
        
        self.needLoadData = YES;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"优惠券";

    [self setupHeaderView];
    [self setupBottomView];
    
    if (self.needLoadData) {
        
        self.page = 1;
        [self getCouponsDatas];
        
        @weakify(self)
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self)
            self.page = 1;
            [self getCouponsDatas];
        }];
        
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            self.page++;
            [self getCouponsDatas];
        }];
        
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTCouponModel *model = self.dataArray[indexPath.row];
    TTCouponViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:model isInvalid:NO];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTCouponModel *model = self.dataArray[indexPath.row];
    if (self.selectedCoupon) {
        self.selectedCoupon(model, self);
    } else {
        [LLRouteTool gotoHomeViewController];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

- (void)getCouponsDatas
{
    NSDictionary *dic = @{
        @"PageIndex" : @(self.page),
        @"PageSize" : @40,
        @"IsRefresh" : @1,
        @"CouponState" : @(self.couponState)
    };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:getCouponList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        NSArray *array = responseObject;
        for (NSDictionary *dic in array) {
            TTCouponModel *model = [TTCouponModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        [self.tableView.mj_header endRefreshing];
        if (array.count < 40) {
            [self setupFooterView];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.view];
}

// 不使用优惠券
- (void)notUseCouponClick
{
    if (self.selectedCoupon) {
        self.selectedCoupon(nil, self);
    }
}

// 查看无效券
- (void)lookInvalidCouponClick
{
    TTInvalidCouponViewController *invalidVC = [[TTInvalidCouponViewController alloc] init];
    [self.navigationController pushViewController:invalidVC animated:YES];
}

// 兑换优惠券
- (void)exchangeBtnClick
{
    if (self.tf.text.length == 0) {
        [self.view makeToast:@"请输入正确的兑换码" duration:1 position:CSToastPositionCenter];
        return;
    }
    NSDictionary *dic = @{
        @"param.couponCode" : self.tf.text,
        @"param.source" : @"淘托APP",
//        @"param.taskNo" : @"" // 新手任务id
    };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:exchangeCoupon_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self.view makeToast:@"兑换成功"];
        self.page = 1;
        [self getCouponsDatas];
        self.tf.text = @"";
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        
        
    } showLoadingInView:self.view];
    
}

- (void)setupHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    
    UIView *tfBGview = [[UIView alloc] initWithFrame:CGRectMake(10, 5, 300 * kScale, 30)];
    tfBGview.backgroundColor = [UIColor whiteColor];
    tfBGview.layer.cornerRadius = 15;
    [headerView addSubview:tfBGview];
    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(15, 0, tfBGview.width - 15, tfBGview.height)];
    tf.delegate = self;
    [tf setPlaceholder:@"请输入兑换码" lightColor:UIColorHex(C7C6CC) darkColor:UIColorHex(C7C6CC)];
    tf.font = [UIFont systemFontOfSize:12];
    tf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [tfBGview addSubview:tf];
    self.tf = tf;
    
    UIButton *exchangeBtn = [UIButton createButtonWithTitle:@"兑换" titleColor:UIColorHex(673AB7) titleFont:[UIFont systemFontOfSize:18] backgroundColor:nil target:self action:@selector(exchangeBtnClick)];
    [headerView addSubview:exchangeBtn];
    [exchangeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.equalTo(headerView);
        make.right.equalTo(headerView).mas_offset(-10);
    }];
    
    self.tableView.tableHeaderView = headerView;
    
}

- (void)setupFooterView
{
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    UILabel *label = [UILabel labelWithTitle:@"没有更多券了 |" color:UIColorHex(999999) fontSize:12];
    [footerView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(footerView);
        make.right.equalTo(footerView.mas_centerX);
    }];
    
    UIButton *btn = [UIButton createButtonWithTitle:@" 查看无效券" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:12] backgroundColor:nil target:self action:@selector(lookInvalidCouponClick)];
    [footerView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_right);
        make.centerY.equalTo(label);
    }];
    
    self.tableView.tableFooterView = footerView;
    
}

- (void)setupBottomView
{
    if (self.showNotUseCoupon) {
        UIButton *btn = [UIButton createButtonWithTitle:@"不使用优惠券" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(notUseCouponClick)];
        [self.view addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.height.mas_equalTo(bottomViewH);
        }];
    }
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.estimatedRowHeight = 130;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        [_tableView registerClass:[TTCouponViewCell class] forCellReuseIdentifier:cellID];
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview:_tableView];
        
        CGFloat bottomH = self.showNotUseCoupon ? bottomViewH : 0;
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-bottomH);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



@end
